<template>
  <base-load-page :loadState="false" class="base-load-page">
    <template #head>
      <div style="padding-bottom: 15px" class="head-box">
        <div class="left-box">
          <base-input-search
            v-model="filterData.createBy"
            clearable
            placeholder="请输入用户"
            style="width: 100%"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
        </div>
        <div class="right-box">
          <el-button type="success" :icon="IconSolarAddCircleLinear" @click="handleAdd">新增</el-button>
        </div>
      </div>
    </template>
    <el-table
      ref="elTableRef"
      v-loading="baseData.loading"
      border
      height="100%"
      :data="tableData"
      :spanMethod="spanMethodsHandler"
      showOverflowTooltip
      stripe
      style="width: 100%"
    >
      <template #empty>
        <base-empty :description="description" :pageLoadButton="[{ text: '重新加载', callBack: () => getAxiosData() }]"></base-empty>
      </template>
      <el-table-column label="查看账号" prop="createBy" minWidth="120">
        <template #default="{ row }">
          {{ row.createBy }}
        </template>
      </el-table-column>
      <el-table-column label="查看短剧" prop="dramaTitle" minWidth="120"></el-table-column>
      <el-table-column label="查看金额权限" prop="createBy" minWidth="120">
        <template #default="{ row }">
          <div style="width: 100px">
            <el-switch
              v-model="row.seeMoney"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              activeText="开"
              inactiveText="关"
              :activeValue="1"
              :inactiveValue="0"
              @change="changeJurisdiction(row)"
            ></el-switch>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <template #foot>
      <div class="pagination-box">
        <el-pagination
          v-model:currentPage="filterData.current"
          v-model:pageSize="filterData.size"
          :pageSizes="[20, 30, 40, 50]"
          :disabled="baseData.loading"
          :pagerCount="13"
          layout="total, prev, pager, next, sizes, jumper"
          :total="baseData.total"
          @change="getAxiosData(true)"
        ></el-pagination>
      </div>
    </template>
    <add-edit ref="addEditRef"></add-edit>
  </base-load-page>
</template>

<script setup lang="ts">
  import IconSearch from '~icons/ep/search';
  import IconSolarAddCircleLinear from '~icons/solar/add-circle-linear';
  import AddEdit from '@/views/app-main/ledger-management/drama-data-view-control/components/add-edit.vue';
  import {
    type DistributionDataControlItem,
    type DistributionDataControlRequest,
    getDistributionDataControlList,
    setDistributionData,
  } from '@/api/ledger-management.ts';
  import type { TableColumnCtx } from 'element-plus';
  const elTableRef: $RefComp<'ElTable'> = ref(null);
  const addEditRef: $RefComp<typeof AddEdit> = ref(null);
  const baseData = shallowReactive({
    type: 'add' as 'add' | 'edit',
    /** 加载状态 */
    loading: true,
    /** 总数量 */
    total: 0,
  });

  const filterData = ref<DistributionDataControlRequest>({
    createBy: '',
    dramaTitle: '',
    current: 1,
    size: 40,
  });

  const tableData = ref<DistributionDataControlItem[]>([]);
  const description = ref('');
  onMounted(() => {
    getAxiosData();
  });

  let spanArr: number[] = [];
  const getSpanArr = (data: DistributionDataControlItem[]) => {
    spanArr = [];
    let pos = 0;
    for (let i = 0; i < data.length; i++) {
      if (i === 0) {
        spanArr.push(1);
        pos = 0;
      } else {
        if (data[i]?.userId === data[i - 1]?.userId) {
          spanArr[pos]! += 1;
          spanArr.push(0);
        } else {
          spanArr.push(1);
          pos = i;
        }
      }
    }
  };

  /**
   * 设置表格数据
   */
  async function getAxiosData(showLoading = true) {
    try {
      await nextTick();
      baseData.loading = Boolean(showLoading);
      const res = await getDistributionDataControlList(filterData.value);
      getSpanArr(res.data.records);
      tableData.value = res.data.records;
      description.value = '暂无数据';
      filterData.value.current = res.data.current;
      filterData.value.size = res.data.size;
      baseData.total = res.data.total;
      baseData.loading = false;
    } catch (error) {
      baseData.loading = false;
      tableData.value = [];
      description.value = error.msg || '加载失败，-BD001';
    }
  }

  const changeJurisdiction = (row: any) => {
    console.log('+==========', row.seeMoney);
    ElMessageBox.confirm('确认操作', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
      beforeClose: async (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true;
          try {
            await setDistributionData(row);
            await getAxiosData(false);
            instance.confirmButtonLoading = false;
            done();
            ElToast.success('修改成功');
          } catch (error) {
            instance.confirmButtonLoading = false;
            ElToast.error(error.msg || '删除失败，-BD004');
          }
        } else {
          row.seeMoney = row.seeMoney ? 0 : 1;
          done();
        }
      },
    });
  };
  /** 跳转到新增视频页面 */
  function handleAdd() {
    addEditRef.value?.show({
      type: 'add',
      addCallBack: () => {
        getAxiosData(false);
      },
    });
  }

  interface SpanMethodProps {
    row: any;
    column: TableColumnCtx<any>;
    rowIndex: number;
    columnIndex: number;
  }
  const spanMethodsHandler = ({ columnIndex, rowIndex }: SpanMethodProps) => {
    if (columnIndex === 0) {
      const _row = spanArr[rowIndex]!;
      const _col = _row! > 0 ? 1 : 0;
      return {
        rowspan: _row,
        colspan: _col,
      };
    }
    if (columnIndex === 2) {
      const _row = spanArr[rowIndex]!;
      const _col = _row! > 0 ? 1 : 0;
      return {
        rowspan: _row,
        colspan: _col,
      };
    }
    return undefined;
  };
</script>

<style lang="scss" scoped>
  .pagination-box {
    @include flex(row, nowrap, center, center, center);
    padding-top: 15px;
  }

  .head-box {
    @include flex(row, nowrap, flex-start, center, center);

    .left-box {
      display: grid;
      flex: 1;
      grid-template-columns: repeat(auto-fill, minmax(210px, 1fr));
      grid-gap: 15px;
      margin-right: 15px;
    }
  }
</style>
